package com.itcy7.service;

import com.itcy7.utils.dto.AppInfoDto;
import com.itcy7.dao.AppInfoDao;
import com.itcy7.dao.AppVersionDao;
import com.itcy7.entity.AppInfo;
import com.itcy7.entity.AppVersion;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.io.File;
import java.util.List;

@Service
public class AppInfoService {

    @Autowired
    AppInfoDao appInfoDao;

    @Autowired
    AppVersionDao appVersionDao;

    public PageInfo<AppInfo> findPage(AppInfoDto appInfoDto, Integer pageNow) {
        PageHelper.startPage(pageNow,8,"id desc");
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        List<AppInfo> appInfoList = appInfoDao.queryAll(appInfo);
        return new PageInfo<>(appInfoList);
    }

    public void addAppInfo(AppInfo appInfo) {
        appInfoDao.insert(appInfo);
    }

    public void updateAppInfo(AppInfo appInfo) {
        appInfoDao.update(appInfo);
    }

    public AppInfo findAppOne(Long appid) {
        AppInfo appInfo = appInfoDao.queryById(appid);
        return appInfo;
    }

    public Boolean findApk(AppInfo appInfo) {
        if(appInfo.getId()!=null){
            AppInfo info = appInfoDao.queryById(appInfo.getId());
            if(info.getApkname().equals(appInfo.getApkname())){
                return true;
            }
        }

        AppInfo app = new AppInfo();
        app.setApkname(appInfo.getApkname());
        int count = (int) appInfoDao.count(app);
        if(count>0){
            return false;
        }else{
            return true;
        }
    }

    public void delAppInfo(Long appid, HttpServletRequest request) {
        AppVersion appVersion = new AppVersion();
        appVersion.setAppid(appid);
        List<AppVersion> appVersionList = appVersionDao.queryAll(appVersion);
        for (AppVersion version : appVersionList) {
            if(StringUtils.hasText(version.getDownloadlink())){
                File file = new File(request.getServletContext().getRealPath(version.getDownloadlink()));
                if(file.exists()){
                    file.delete();//删除对应手游版本所有apk文件
                }
            }
            appVersionDao.deleteById(version.getId()); //删除对应手游所有版本
        }

        AppInfo appInfo = appInfoDao.queryById(appid);
        if(StringUtils.hasText(appInfo.getLogopicpath())){
            File file = new File(request.getServletContext().getRealPath(appInfo.getLogopicpath()));
            if(file.exists()){
                file.delete();//删除对应手游logo图片
            }
        }

        appInfoDao.deleteById(appid);
        //删除对应手游信息
    }
}
